package org.promote.hotspot.client.callback;

import lombok.extern.slf4j.Slf4j;
import org.promote.hotspot.client.cache.CacheFactory;
import org.promote.hotspot.client.filter.HotSpotDetector;
import org.promote.hotspot.client.model.ValueModel;
import org.promote.hotspot.common.model.HotKeyModel;
import org.promote.hotspot.common.tool.SystemClock;

/**
 * 处理来自于的server新增key事件
 * @author enping.jep
 * @date 2024/02/05 14:00
 **/
@Slf4j
public class DefaultNewKeyListener implements ReceiveNewKeyListener {
    @Override
    public void newKey(HotKeyModel hotKeyModel) {
        long now = SystemClock.now();
        //如果key到达时已经过去1秒了，记录一下。
        if (hotKeyModel.getCreateTime() != 0 && Math.abs(now - hotKeyModel.getCreateTime()) > 1000) {
            log.warn("the key comes too late : " + hotKeyModel.getKey() + " now " +
                    +now + " keyCreateAt " + hotKeyModel.getCreateTime());
        }

        //已经是热键了，然后又被推送了一次
        if (HotSpotDetector.isHot(hotKeyModel.getKey())) {
            log.warn("receive repeat hot key ：" + hotKeyModel.getKey() + " at " + now);
        }
        addKey(hotKeyModel.getKey());
    }

    private void addKey(String key) {
        ValueModel valueModel = ValueModel.defaultValue(key);
        if (valueModel == null) {
            //不符合任何规则
            deleteKey(key);
            return;
        }
        //如果原来该key已经存在了，那么value就被重置，过期时间也会被重置。如果原来不存在，就新增的热key
        HotSpotDetector.setValueDirectly(key, valueModel);
    }

    private void deleteKey(String key) {
        CacheFactory.getNonNullCache(key).delete(key);
    }
}